#! /usr/bin/env python
#coding=utf-8

import os
import struct

# find out/rk3568/packages/phone/system/ -type f -print | file -f - | grep ELF | cut -d":" -f1 | wc -l
# https://github.com/horsicq/XMachOViewer

class MachOWalker():
	def __init__(self, path="/Users/handy/Documents/work/apple/projects/OSInspect/macOS_dylibs"):
		self._files = []
		self._links = {}
		self._walked = False
		self._path = path

	def __walk_path(self):
		for root, subdirs, files in os.walk(self._path):
			for _filename in files:
				_assetFile = os.path.join(root, _filename)
				if not os.path.isfile(_assetFile):
					continue
				#if _assetFile.find(".dylib") > 0:
				#	self._files.append(_assetFile)
				with open(_assetFile, "rb") as f:
					data = f.read(4)
					try:
						magic = struct.unpack("BBBB", data)
						if magic[0] == 0xCF and magic[1] == 0xFA and magic[2] == 0xED and magic[3] == 0xFE:
							self._files.append(_assetFile)
					except:
						pass

		self._walked = True

	def get_path(self):
		return self._path

	def get_all_files(self):
		if not self._walked:
			self.__walk_path()
		return self._files

if __name__ == '__main__':
	dylibFiles = MachOWalker()
	#for f in dylibFiles.get_dylib_files():
	#	print(f)

	print("Total: %d macho" % (len(dylibFiles.get_all_files())))
